package com.onpositive.notes.android.tools;

import java.util.ArrayList;
import java.util.Set;

import android.content.Context;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;

import com.onpositive.businessdroids.model.IField;
import com.onpositive.businessdroids.model.impl.AbstractCollectionBasedModel;
import com.onpositive.businessdroids.ui.IViewer;
import com.onpositive.businessdroids.ui.dataview.StructuredDataView;
import com.onpositive.businessdroids.ui.dataview.renderers.IFieldRenderer;
import com.onpositive.notes.impl.BasicNote;
import com.onpositive.notes.model.INote;
import com.onpositive.notes.parser.BasicNoteParser;
import com.onpositive.notes.services.BasicNoteRegistry;
import com.onpositive.notes.services.TemplateModelRegistry;

public class NoteRecordRenderer implements IFieldRenderer {
	
	String[] STRING_REALM ;
	ArrayAdapter<String> adapter ;
	SpaceTokenizer tokenizer = new SpaceTokenizer() ;
	TextView lastView = null ;
	
	@Override
	public void setPropValueToView(View renderedField, IField column,
			Object fieldValue, IViewer table, Object parenObj) {
		
		if( !(renderedField instanceof TextView) )
			return ;
		
		if(!(fieldValue instanceof INote))
			return ;
		
		TextView txt = (TextView) renderedField ;
		INote note = (INote) fieldValue ;
		
		txt.setText( note.getInitialText() ) ;		
	}
	
	@Override
	public View renderField(IField column, Object fieldValue, final IViewer table, Object object )
	{
		
		Context context = table.getContext();
		
		
		if( STRING_REALM == null ){
			
			Set<String> allTemplateKeys = TemplateModelRegistry.getInstance().getAllTemplateKeys();
	        ArrayList<String> lst = new ArrayList<String>( allTemplateKeys ) ;
	        STRING_REALM = lst.toArray( new String[ lst.size() ] ) ;
	        
	        adapter = new ArrayAdapter<String>(context,
	                android.R.layout.simple_dropdown_item_1line, STRING_REALM);
		}	
		
		final MultiAutoCompleteTextView txt = new MultiAutoCompleteTextView( context ){			

			@Override
			public String toString(){
				return getText().toString() ;
			}
		};
        txt.setTokenizer( tokenizer );
        txt.setAdapter(adapter) ;
        TextColorProvider colorProvider = new TextColorProvider(txt);
		txt.addTextChangedListener( colorProvider ) ;
        
        
        txt.setPadding(4, 0, 4, 0) ;
        switchViewOff(txt) ;
        
        final INote[] oldNote = new INote[1] ;
        if(fieldValue instanceof INote){		
        	INote note = (INote) fieldValue ;
        	oldNote[0] = note ;
        	colorProvider.setInitialBlocks( note.getBlocks() ) ;
        	colorProvider.setInitialString( note.getInitialText() ) ;
        	txt.setText( note.getInitialText() ) ;		
        }
        else if ( fieldValue instanceof String ){
        	String str = (String) fieldValue ;
        	txt.setText( str ) ;
        }        
        
        txt.setOnTouchListener( new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				boolean superResult = v.onTouchEvent(event);
				if( !superResult || !(v instanceof TextView) )					
					return superResult;
				
				TextView tv = (TextView) v ;
				switchViewOn(tv);
				
				if(lastView != null && lastView != tv)
					switchViewOff(lastView) ;
				
				lastView = tv ;
				return superResult ;
			}
		}) ;
        
        txt.setOnFocusChangeListener( new View.OnFocusChangeListener() {
			
        	@Override
			public void onFocusChange(View v, boolean hasFocus) {
				
				while(true){
					if( hasFocus )
						break ;
					
					if( !(v instanceof TextView) )
						break ;
					
					if( v != txt )
						break ;
					
					TextView tv = (TextView) v ;
					
					String newStr = tv.getText().toString() ;
					INote note = oldNote[0] ;
					if(note != null && newStr.trim().equals(note.getInitialText().trim()))				
						break ;
				
					INote newNote = new BasicNoteParser().parse(newStr) ;

					BasicNoteRegistry.getInstance().unRegisterNote(note) ;
					((BasicNote)note).copyContent(newNote) ;
					BasicNoteRegistry.getInstance().registerNote(note) ;
					
					break ;
				}
			}			
		}) ;
		return txt ;
	}
	
	protected void switchViewOn(TextView tv) {
		tv.setMinLines(0);
		tv.setMaxLines(Integer.MAX_VALUE) ;
		tv.setBackgroundColor( Color.WHITE ) ;
		tv.refreshDrawableState() ;		
	}
	
	protected void switchViewOff(TextView tv) {		
		tv.setLines(1) ;
		tv.setBackgroundColor( Color.TRANSPARENT ) ;
		tv.refreshDrawableState() ;
	}

}
